import { removeToken, setToken } from "@/utils/auth"
import { useTagsView } from "./tagsView"
import {
  Profile,
  IUserQuery,
  IUsers,
  login as loginApi,
  getUsers as getUsersApi,
  addUser as addUserApi,
  removeUser as removeUserApi,
  updateUser as updateUserApi
} from "@/api/user"

export interface IUserInfo {
  username: string
  password: string
}
export type IProfileQuery = Profile & {
  pageNum?: number
  pageSize?: number
}

export const useUserStore = defineStore("user", () => {
  const state = reactive({
    token: "",
    users: [] as IUsers["users"], // 用户列表
    count: 0 // 用户个数
  })
  const login = async (userInfo: IUserInfo) => {
    try {
      const { username, password } = userInfo
      const response = await loginApi({ username: username.trim(), password })
      const { data } = response
      state.token = data.token
      setToken(data.token)
    } catch (e) {
      return Promise.reject(e)
    }
  }
  const resetToken = () => {
    state.token = ""
    removeToken()
  }
  const { delAllView } = useTagsView()
  const logout = () => {
    resetToken()
    delAllView()
  }

  const getAllUsers = async (params: IUserQuery) => {
    const res = await getUsersApi(params)
    const { data } = res
    state.users = data.users
    state.count = data.count
  }

  const addUser = async (data: IProfileQuery) => {
    const { pageSize, pageNum, ...params } = data
    const res = await addUserApi(params)
    if (res.code === 0) {
      getAllUsers({ pageSize, pageNum })
    }
  }

  const removeUser = async (data: IProfileQuery) => {
    const { pageSize, pageNum, id } = data
    const res = await removeUserApi(id)
    if (res.code === 0) {
      getAllUsers({ pageSize, pageNum })
    }
  }

  const editUser = async (data: IProfileQuery) => {
    const { pageSize, pageNum, ...params } = data
    const res = await updateUserApi(params.id, params)
    if (res.code === 0) {
      getAllUsers({ pageSize, pageNum })
    }
  }

  return {
    state,
    login,
    logout,
    resetToken,
    getAllUsers,
    addUser,
    editUser,
    removeUser
  }
})
